﻿using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;

namespace MetadataDesignerLibrary
{
    public class AssemblyReferenceRule : ILRule<AssemblyReferenceHandle>
    {
        [ILInfo(true)]
        public string Name { get; }

        [ILInfo]
        public Version Version { get; }

        [ILInfo]
        public string Culture { get; }

        [ILInfo]
        public byte[] PublicKeyOrToken { get; }

        [ILInfo]
        public AssemblyFlags Flags { get; }

        [ILInfo]
        public byte[] HashValue { get; }

        [ILInfo(true, ILInfoParseMethod.AsString)]
        public AssemblyName AssemblyName { get; }

        [ILInfo(ILInfoParseMethod.AsEntityHandleCollection)]
        public CustomAttributeHandleCollection CustomAttributes { get; }

        public AssemblyReferenceRule(
            string name,
            Version version,
            string culture,
            byte[] publicKeyOrToken,
            AssemblyFlags flags,
            byte[] hashValue)
            : base()
        {
            Name = name;
            Version = version;
            Culture = culture;
            PublicKeyOrToken = publicKeyOrToken;
            Flags = flags;
            HashValue = hashValue;
        }

        public AssemblyReferenceRule(MetadataReader reader, AssemblyReferenceHandle assemblyReferenceHandle)
            : base(reader)
        {
            AssemblyReference assemblyReference = reader.GetAssemblyReference(assemblyReferenceHandle);
            Culture = reader.GetString(assemblyReference.Culture);
            Flags = assemblyReference.Flags;
            HashValue = reader.GetBlobBytes(assemblyReference.HashValue);
            Name = reader.GetString(assemblyReference.Name);
            PublicKeyOrToken = reader.GetBlobBytes(assemblyReference.PublicKeyOrToken);
            Version = assemblyReference.Version;
            AssemblyName = assemblyReference.GetAssemblyName();
            CustomAttributes = assemblyReference.GetCustomAttributes();
        }

        public override AssemblyReferenceHandle Write(MetadataDesigner designer)
        {
            MetadataBuilder builder = designer.Builder;
            return builder.AddAssemblyReference(
                name: Name == null ? default : builder.GetOrAddString(Name),
                version: Version,
                culture: Culture == null ? default : builder.GetOrAddString(Culture),
                publicKeyOrToken: PublicKeyOrToken == null ? default : builder.GetOrAddBlob(PublicKeyOrToken),
                flags: Flags,
                hashValue: HashValue == null ? default : builder.GetOrAddBlob(HashValue));
        }
    }
}